/**
 *  ward @ 2019
 *  harrydeep@wardyan.top
 */
package top.wardyan.tool;

import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;

import com.alibaba.druid.filter.config.ConfigTools;
import com.alibaba.fastjson.JSONArray;

import top.wardyan.base.action.BaseShell;
import top.wardyan.base.config.Const;
import top.wardyan.base.config.SystemConfig;
import top.wardyan.base.util.DateUtil;
import top.wardyan.base.util.swt.Msg;
import top.wardyan.tool.po.Conf;
import top.wardyan.tool.po.ConfItem;

/**
 * 配置管理器
 * @author ward
 *
 * 2019年2月17日
 */
public class AppConfigConfigure extends BaseShell<AppConfigConfigure>{
	
	protected Logger log = Logger.getLogger(this.getClass());
	
	protected String filename = "AppConfig.properties";
	
	protected String targetFileName = "AppConfig.txt";
	// protected Prop prop = PropKit.use(filename);
	
	protected Properties current = null; 
	
	//protected List<>
	protected Properties prop = null;
	protected List<Text> texts = new ArrayList<>();
	
	protected void load() {
		current = new Properties();
		try(FileReader reader = new FileReader(targetFileName)){
			current.load(reader);
		}catch(Exception e) {
			log.error(e);
		}
		
		prop = new Properties();
		try(FileReader reader = new FileReader(filename)){
			prop.load(reader);
		}catch(Exception e) {
			log.error(e);
		}
	}
	
	protected void save() {
		if(current != null) {
			try(FileWriter writer = new FileWriter(targetFileName)){
				current.store(writer, "配置文件: 决定配置管理工具应该往AppConfig.txt中写入哪些项目. 创建时间:" + DateUtil.formatNow());
				Msg.showMessage("操作结果", "保存成功");
			}catch(Exception e) {
				log.error(e);
			}
		}
	}
	
	public AppConfigConfigure() {
		this(false);
	}
	
	public Boolean autoClose;
	
	public AppConfigConfigure(Boolean autoClose) {
		super();
		this.autoClose = autoClose;
		load();
		createContent();
	}
	
	protected void createContent() {
		Label title = new Label(this, SWT.NONE);
		title.setText("配置管理器");
		title.setAlignment(SWT.CENTER);
		title.setBounds(0, 20, this.getSize().x, 50);
		title.setFont(Const.FONT_TITLE);
		title.setBackground(Const.COLOR_WHITE);
		
		Integer labelSize = this.getSize().x / 12;
		Integer textSize = labelSize * 17 / 10;
		if(prop != null) {
			String classifications = prop.getProperty("classification");
			List<Conf> confs = null;
			if(classifications != null) {
				confs = JSONArray.parseArray(classifications, Conf.class);
				if(confs != null) {
					Composite prev = null;
					for(Conf c : confs) {
						Composite com = new Composite(this, SWT.NONE);
						com.setBackground(Const.COLOR_WHITE);
						if(prev != null) {
							com.setBounds(30, prev.getLocation().y + prev.getSize().y + 5, this.getSize().x - 60, 70);
						}else {
							com.setBounds(30, title.getLocation().y + title.getSize().y + 5, this.getSize().x - 60, 70);
						}
						prev = com;
						Label category = new Label(com, SWT.NONE);
						category.setText(c.getName());
						category.setFont(Const.FONT_H7);
						category.setBounds(0, 0, com.getSize().x, 30);
						category.setBackground(Const.COLOR_WHITE);
						String itemstrs = prop.getProperty("classification_" + c.getPrefix());
						List<ConfItem> items = JSONArray.parseArray(itemstrs, ConfItem.class);
						if(items != null) {
							Label prevLabel = null;
							Integer i = 0;
							Integer y = category.getLocation().y + category.getSize().y + 5;
							for(ConfItem item : items) {
								Label label = new Label(com, SWT.NONE);
								label.setText(item.getName());
								label.setAlignment(SWT.RIGHT);
								label.setFont(Const.FONT_H8);
								label.setBackground(Const.COLOR_WHITE);
								if(item.getRequired())
									label.setText(label.getText() + "*");
								if(i > 3) {
									prevLabel = null;
									y += 30;
									i = 0;
									com.setSize(com.getSize().x, com.getSize().y + 40);
								}
									
								label.setBounds(prevLabel != null ? prevLabel.getLocation().x + textSize + labelSize + 10 : 0, y, labelSize, 23);
								prevLabel = label;
								Text text = new Text(com, SWT.BORDER);
								text.setBounds(label.getLocation().x + labelSize + 5, y, textSize, label.getSize().y);
								text.setFont(Const.FONT_H8);
								String name = c.getPrefix() + "_" + item.getCode();
								text.setData("name", name);
								text.setData("required", item.getRequired());
								text.setData("encoded", item.getEncoded());
								
								//System.out.println(text.getData());
								text.setText(current.getProperty(name, ""));
								text.setTextLimit(item.getMaxLength() != null && item.getMaxLength() > 0 ? item.getMaxLength() : 255);
								texts.add(text);
								i ++;
							}
						}
					}
					Button btn = new Button(this, SWT.NONE);
					btn.setText("保存");
					btn.setSize(80, 30);
					btn.setLocation(this.getSize().x - 120, prev != null ? prev.getLocation().y + prev.getSize().y + 30 : title.getSize().y + title.getLocation().y + 30);
					// listener
					btn.addSelectionListener(this.getButtonAdapter());
				}
				
			}
		}
	}
	
	/** 检查输入. 默认检查必填项是否已填. 如果检查返回false,则断点不再执行保存 **/
	protected Boolean check() {
		Boolean rs = true;
		for(Text text : texts) {
			if(text.getData("required") != null && (Boolean)text.getData("required") && (text.getText().length() == 0)) {
				rs = false;
				text.setFocus();
				break;
			}
		}
		return rs;
	}
	
	/** 将配置文件写入 **/
	protected void writeProp() {
		//prop.clear();
		for(Text text : texts) {
			if(!text.getText().equals(current.getProperty((String) text.getData("name")))) {	// 只有跟原来的不同才改
				if(text.getData("encoded") != null && (Boolean)text.getData("encoded"))
					try {
						current.put(text.getData("name"), ConfigTools.encrypt(SystemConfig.PrivateKey, text.getText()));
					} catch (Exception e) {
						current.put(text.getData("name"), text.getText());
					}
				else
					current.put(text.getData("name"), text.getText());
			}
		}
		this.save();
	}
	
	/** 处理保存按钮的时间 **/
	protected SelectionAdapter getButtonAdapter() {
		SelectionAdapter rs = new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				super.widgetSelected(e);
				if(check()) {
					writeProp();
					if(self.autoClose)
						self.dispose();
				}else {
					Msg.showMessage("错误", "未通过check检查");
				}
			}
		};
		
		return rs;
	}
	
	
	/**
	 Properties prop = new Properties();
		
		
		
		prop.load(new FileReader(filename));
		
		prop.setProperty("name", "名称");
		prop.setProperty("value", "值");
		//prop.save(new FileOutputStream(filename), "配置文件");
		prop.store(new FileWriter(filename), "配置文件");
	 */
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	public static void main(String[] args) {
			new AppConfigConfigure(true).go();
		
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
}
